<template>
  <div class="app-container editManage">
    <el-card :body-style="{ 'padding-left': '40px' }">
      <el-tabs v-model="activeName">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="0">
          <el-form
            ref="queryForm"
            :model="form"
            label-position="top"
            label-width="100px"
            label-suffix=":"
            :rules="rules"
            v-if="loadingForm"
          >
            <dk-form
              :form-input="formList"
              :span-num="1"
              :rule-form="form"
            >
              <template #videoUrl="{ row }">
                <video
                  v-if="form[row.name] != ''"
                  :src="domain + form[row.name]"
                  style="width: 100px; height: 100px"
                  controls
                ></video>
                <VideoUpload
                  v-else
                  v-model="form[row.name]"
                  :file-size="row.fileSize || 100"
                  :tips-text="row.tipsText"
                />
              </template>
            </dk-form>
          </el-form>
        </el-tab-pane>
        <!-- 规格设置 -->
        <el-tab-pane label="规格设置" name="1">
          <el-form
            ref="rosForm"
            :model="rosForm"
            label-position="top"
            label-width="100px"
            label-suffix=":"
            :rules="rosRules"
          >
            <el-form-item
              label="规格类型"
              label-width="120px"
              prop="isType"
              style="
                text-align: left;
                display: grid;
                grid-template-columns: 0px 100px auto;
              "
            >
              <el-radio-group v-model="isType">
                <el-radio :label="0">单规格</el-radio>
                <el-radio :label="1">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 单规格 -->
            <dk-form
              v-if="isType == 0"
              :form-input="resFormList"
              :span-num="1"
              :rule-form="rosForm"
            />
          </el-form>
          <!-- 多规格 -->
          <el-form
            v-if="isType === 1"
            ref="mulForm"
            :model="mulForm"
            label-position="top"
            label-width="100px"
            label-suffix=":"
            :rules="mulRules"
          >
            <dk-form
              :form-input="mulFormList"
              :span-num="1"
              :rule-form="mulForm"
            />

            <!-- sku -->
            <el-form-item
              label=""
              label-width="120px"
              prop="specification"
              style="position: relative"
            >
              <div>
                <div class="goods-spec">
                  <div style="display: flex; align-items: center">
                    <h3
                      style="
                        font-weight: 700;
                        font-size: 14px;
                        color: #606266;
                      "
                    >
                      商品规格：
                    </h3>
                    <p
                      style="
                        color: #cbcbcb;
                        font-size: 12px;
                        margin-left: 30px;
                      "
                    >
                      最多添加3个商品规格
                    </p>
                  </div>
                  <el-link
                    type="primary"
                    class="goods-spec-add"
                    @click="addPriSpec"
                    >添加规格</el-link
                  >
                </div>
                <div
                  v-for="(attr, index) in items"
                  :key="'goods' + index"
                  class="goods-container"
                >
                  <div class="goods-content">
                    <div class="goods-content-box">
                      <div class="goods-content-left">
                        <el-form label-width="80px">
                          <el-form-item
                            label="规格名"
                            style="width: 30%"
                          >
                            <el-input
                              v-model="attr.groupName"
                              placeholder="请输入规格名"
                            />
                          </el-form-item>
                          <el-form-item label="规格值">
                            <el-tag
                              v-for="(tag, tagIndex) in attr.detail"
                              :key="'detail' + tagIndex"
                              closable
                              :disable-transitions="false"
                              @close="handleClose(tag, attr, index)"
                            >
                              {{ tag }}
                            </el-tag>
                            <el-input
                              v-if="attr.inputVisible"
                              :ref="`saveTagInput${index}`"
                              v-model="attr.inputValue"
                              class="input-new-tag"
                              :class="'saveTagInput' + index"
                              size="small"
                              @keyup.enter.native="
                                handleInputConfirm(
                                  attr.inputValue,
                                  attr
                                )
                              "
                              @blur="
                                handleInputConfirm(
                                  attr.inputValue,
                                  attr
                                )
                              "
                            />
                            <el-button
                              v-else
                              class="button-new-tag"
                              size="small"
                              @click="showInput(attr, index)"
                              >+ 添加</el-button
                            >
                          </el-form-item>
                        </el-form>
                      </div>
                      <div class="goods-content-right">
                        <el-link
                          type="danger"
                          @click="delPrivateSpec(index)"
                          >删除规格</el-link
                        >
                      </div>
                    </div>
                  </div>
                </div>

                <div v-for="(t, i) in items" :key="'sku' + i">
                  <p
                    style="
                      margin: 24px 0 10px 0;
                      font-weight: 700;
                      font-size: 14px;
                      color: #606266;
                    "
                  >
                    {{ t.groupName || 'sku列表' + i }}
                  </p>
                  <el-table
                    ref="multipleTable"
                    :data="tableColumnList.tableBodyList[i]"
                    stripe
                    tooltip-effect="dark"
                    style="width: 100%; margin-top: 1%"
                  >
                    <el-table-column
                      v-for="item in tableColumnList.tableHeaderList"
                      :key="item.label"
                      :label="item.label"
                      :show-method="item.showMethod"
                      :prop="item.prop"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <span v-if="item.showMethod === 'number'">{{
                          scope.row[scope.column.property]
                        }}</span>
                        <el-input
                          v-else-if="item.showMethod === 'input'"
                          v-model="scope.row[scope.column.property]"
                          placeholder="请输入"
                          @change="changeNum(scope, scope.$index)"
                        />
                        <ImageUpload
                          v-else-if="item.showMethod === 'img'"
                          v-model="scope.row[scope.column.property]"
                          :limit="1"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-card
      style="margin-top: 20px"
      :body-style="[{ 'padding-left': '40px' }]"
    >
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </el-card>
  </div>
</template>
<script>
// 接口api：first step
import {
  addGoodsBaseType,
  editGoodsBaseType,
  getGoodsBaseInfo,
} from '@/api/list/shop-list.js';
import { getGoodsTypeList } from '@/api/class/commodity-class.js';
// 获取模板
import { freightTemplateList } from '@/api/list/freight-template.js';
import { imgDomain } from '@/configs/env';
export default {
  data() {
    // 单规格：积分可抵扣
    // 规则：正整数，不允许超过数值100
    var validatePoint = (rule, value, callback) => {
      if (+value >= 100) {
        callback(new Error('商品金额需大于积分抵扣金额'));
      }

      callback();
    };

    // 单规格：定金取值方式 - %
    // 规则：不允许超过3位数
    var rmbLength = (rule, value, callback) => {
      // 购买方式为1-定金且定金单位为0-百分比才进行判断
      if (
        this.rosForm['depositUnit'] == 0 &&
        this.rosForm['purchaseType'] == 1
      ) {
        if (value.length > 3) {
          callback(new Error('不允许超过3位'));
        }
      }
      callback();
    };
    // 单规格：定金取值方式 - %
    // 规则：正整数
    var validateRmbRos = (rule, value, callback) => {
      if (!this.rosForm['purchaseType']) callback();
      if (this.rosForm['depositUnit'] == 0) {
        if (+value % 1 !== 0 || +value <= 0) {
          callback(new Error('请输入正整数'));
        }
      }
      callback();
    };

    // 单规格：定金取值方式 - 元
    // 规则：正数，没有位数限制
    var validateYuan = (rule, value, callback) => {
      if (this.rosForm['depositUnit'] == 1) {
        if (+value < 0) {
          callback(new Error('请输入正数'));
        }
      }
      callback();
    };
    // 多规格：定金取值方式 - %
    // 规则：正整数，不允许超过3位数
    var validateRmbMul = (rule, value, callback) => {
      if (!this.mulForm['purchaseType']) callback();
      if (this.mulForm['depositUnit'] == 0) {
        if (+value % 1 !== 0 || +value <= 0) {
          callback(new Error('请输入正整数'));
        }
      }
      callback();
    };
    // 多规格：定金取值方式 - %
    // 规则：不允许超过3位数
    var rmbLengthMul = (rule, value, callback) => {
      // 购买方式为1-定金且定金单位为0-百分比才进行判断
      if (
        this.rosForm['depositUnit'] == 0 &&
        this.rosForm['purchaseType'] == 1
      ) {
        if (value.length > 3) {
          callback(new Error('不允许超过3位'));
        }
      }
      callback();
    };
    // 多规格：定金取值方式 - 元
    // 规则：正数，没有位数限制
    var validateYuanMul = (rule, value, callback) => {
      if (this.mulForm['depositUnit'] == 1) {
        if (+value < 0) {
          callback(new Error('请输入正数'));
        }
      }
      callback();
    };
    return {
      loadingForm: false,
      // 商品类别，1: 店铺商品，2:会员服务商品，3:  自营商品
      type: 1,
      // 0基础信息 1规格设置
      activeName: '0',
      // 0单规格，1多规格
      isType: 0,
      loading: false,
      // table索引
      tableBodyListIndex: 0,
      domain: imgDomain,
      // 表单对象：two step
      form: {
        goodsName: '',
        subName: '',
        goodsTypeName: '',
        goodsTypeRos: [],
        sort: 0,
        freightTemplateId: '',
        initialSalesVolume: 0,
        promotionTime: [],
        coverImg: '',
        carousel: [],
        // 所属门店id
        shopId: '',
        videoUrl: '',
        detail: '',
        brandId: '',
        /* 以下0:否,1:是 */
        // 是否促销
        isPromotion: 0,
        // 是否显示在对应店铺
        isShowInBrand: 0,
        // 是否上架
        isGrounding: 0,
        // 是否精选
        isSelected: 0,
      },
      // 单规格数据
      rosForm: {
        // 购买方式，0：全款，1定金
        purchaseType: 0,
        inventory: '',
        inventoryAlert: '',
        platformPrice: '',
        costPrice: '',
        crossedPrice: '',
        pointDeductionPercentage: 0,
        depositPercentage: 0,
        // 定金单位，0-百分比，1-元
        depositUnit: 0,
        weight: 0,
      },
      // 多规格数据
      mulForm: {
        // 购买方式，0：全款，1定金
        purchaseType: 0,
        pointDeductionPercentage: 0,
        depositPercentage: 0,
        // 定金单位，0-百分比，1-元
        depositUnit: 0,
      },
      // 表单配置项：three step
      formList: [
        {
          label: '商品名称',
          placeholder: '请输入',
          type: 'input',
          name: 'goodsName',
          prop: 'goodsName',
          maxlength: 30,
        },
        // {
        //   label: '商品副标题',
        //   placeholder: '请输入',
        //   type: 'input',
        //   name: 'subName',
        //   prop: 'subName',
        //   maxlength: 50,
        // },
        {
          label: '商品分类',
          placeholder: '请选择',
          type: 'select-tree',
          name: 'goodsTypeName',
          prop: 'goodsTypeName',
          list: [],
          url: this.network().getGroup,
          props: {
            value: 'id',
            children: 'martGoodsTypeVos',
            label: 'typeName',
          },
          goodsTypeRos: true,
        },
        {
          label: '排序',
          placeholder: '请输入0-999,不输入则默认为0',
          type: 'inputNumber',
          name: 'sort',
          prop: 'sort',
          max: 999,
          maxlength: 3,
          precision: 0,
        },
        {
          label: '是否上架',
          placeholder: '请选择',
          type: 'radio',
          name: 'isGrounding',
          prop: 'isGrounding',
          list: [
            { name: '是', value: 1 },
            { name: '否', value: 0 },
          ],
        },

        // {
        //   label: '是否显示在对应店铺',
        //   placeholder: '请选择',
        //   type: 'radio',
        //   name: 'isShowInBrand',
        //   prop: 'isShowInBrand',
        //   list: [
        //     { name: '是', value: 1 },
        //     { name: '否', value: 0 },
        //   ],
        // },
        {
          label: '是否在首页精选显示',
          placeholder: '请选择',
          type: 'radio',
          name: 'isSelected',
          prop: 'isSelected',
          list: [
            { name: '是', value: 1 },
            { name: '否', value: 0 },
          ],
          // show: (data) => {
          //   return this.form['isPromotion'] ? false : true;
          // },
        },
        {
          label: '是否促销商品',
          placeholder: '请选择',
          type: 'radio',
          name: 'isPromotion',
          prop: 'isPromotion',
          list: [
            { name: '是', value: 1 },
            { name: '否', value: 0 },
          ],
        },

        {
          label: '活动时间',
          placeholder: '请选择活动时间',
          type: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          name: 'promotionTime',
          prop: 'promotionTime',
          show: (data) => {
            return this.form['isPromotion'] ? true : false;
          },
        },
        // {
        //   type: 'select',
        //   placeholder: '请输入',
        //   label: '归属品牌',
        //   name: 'brandId',
        //   prop: 'brandId',
        //   list: [],
        // },
        {
          type: 'select',
          placeholder: '请选择',
          label: '运费模板',
          name: 'freightTemplateId',
          prop: 'freightTemplateId',
          list: [],
        },
        // {
        //   label: '初始销量',
        //   placeholder: '请输入',
        //   type: 'input',
        //   name: 'initialSalesVolume',
        //   prop: 'initialSalesVolume',
        //   maxlength: 30,
        // },
        {
          label: '封面图',
          placeholder: '请上传',
          type: 'imageUpload',
          name: 'coverImg',
          prop: 'coverImg',
          limit: 1,
          tipsText:
            '可上传1张图片，建议尺寸208*208px，大小建议不能超过3M',
        },
        {
          label: '商品轮播图',
          placeholder: '请上传',
          type: 'imageUpload',
          name: 'carousel',
          prop: 'carousel',
          limit: 5,
          tipsText:
            '可上传5张图片，建议尺寸750*750px，大小建议不能超过3M',
        },

        {
          label: '视频',
          placeholder: '请上传',
          type: 'slot',
          name: 'videoUrl',
          prop: 'videoUrl',
          tipsText: '可上传mp4格式，建议尺寸1:1，大小建议不能超过10M',
        },
        {
          label: '商品详情',
          placeholder: '请上传',
          type: 'editor',
          name: 'detail',
          prop: 'detail',
        },
      ],
      // 单规格表单配置项
      resFormList: [
        {
          label: '库存',
          placeholder: '请输入',
          type: 'input',
          name: 'inventory',
          prop: 'inventory',
          maxlength: 5,
          digit: 0,
        },
        {
          label: '库存预警',
          placeholder: '请输入',
          type: 'input',
          name: 'inventoryAlert',
          prop: 'inventoryAlert',
          maxlength: 5,
          digit: 0,
        },
        {
          label: '尊享价(元)',
          placeholder: '请输入',
          type: 'input',
          name: 'platformPrice',
          prop: 'platformPrice',
          maxlength: 10,
          digit: 2,
        },
        // {
        //   label: '成本价(元)',
        //   placeholder: '请输入',
        //   type: 'input',
        //   name: 'costPrice',
        //   prop: 'costPrice',
        //   maxlength: 10,
        // },
        {
          label: '指导价(元)',
          placeholder: '请输入',
          type: 'input',
          name: 'crossedPrice',
          prop: 'crossedPrice',
          maxlength: 10,
          digit: 2,
        },
        // {
        //   label: '积分可抵扣(%)',
        //   placeholder: '填0不使用积分抵扣，在用户端不显示',
        //   type: 'input',
        //   name: 'pointDeductionPercentage',
        //   prop: 'pointDeductionPercentage',
        //   maxlength: 10,
        // },
        {
          label: '购买方式',
          placeholder: '请选择',
          type: 'radio',
          name: 'purchaseType',
          prop: 'purchaseType',
          list: [
            { name: '全款', value: 0 },
            { name: '定金', value: 1 },
          ],
        },
        {
          label: '定金取值方式',
          placeholder: '请选择',
          type: 'append-input',
          name: 'depositPercentage',
          prop: 'depositPercentage',
          unit: 'depositUnit',
          unitList: [
            { label: '%', value: 0 },
            { label: '元', value: 1 },
          ],
          show: (data) => {
            return !!this.rosForm['purchaseType'];
          },
        },
        // 重量
        {
          label: '商品重量(kg)',
          placeholder: '请输入',
          type: 'input',
          name: 'weight',
          prop: 'weight',
          maxlength: 10,
        },
      ],
      // 多规格表单配置项
      mulFormList: [
        // {
        //   label: '积分可抵扣(%)',
        //   placeholder: '填0不使用积分抵扣，在用户端不显示',
        //   type: 'input',
        //   name: 'pointDeductionPercentage',
        //   prop: 'pointDeductionPercentage',
        //   maxlength: 10,
        // },
        {
          label: '购买方式',
          placeholder: '请选择',
          type: 'radio',
          name: 'purchaseType',
          row: true,
          prop: 'purchaseType',
          list: [
            { name: '全款', value: 0 },
            { name: '定金', value: 1 },
          ],
        },
        {
          label: '定金取值方式',
          placeholder: '请选择',
          type: 'append-input',
          name: 'depositPercentage',
          prop: 'depositPercentage',
          unit: 'depositUnit',
          unitList: [
            { label: '%', value: 0 },
            { label: '元', value: 1 },
          ],
          show: (data) => {
            return !!this.mulForm['purchaseType'];
          },
          // maxlength:3,
        },
      ],
      // 校验对象：four step
      rules: {
        goodsName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'change',
          },
        ],
        freightTemplateId: [
          {
            required: true,
            message: '请选择运费模版',
            trigger: 'change',
          },
        ],
        goodsTypeName: [
          {
            required: true,
            message: '请选择商品分组',
            trigger: 'change',
          },
        ],
        isGrounding: [
          {
            required: true,
            message: '请选择是否上架',
            trigger: 'change',
          },
        ],
        isSelected: [
          {
            required: true,
            message: '请选择是否精选',
            trigger: 'change',
          },
        ],
        brandId: [
          {
            required: true,
            message: '请选择归属品牌',
            trigger: 'change',
          },
        ],
        carousel: [
          {
            required: true,
            message: '请上传商品轮播图',
            trigger: 'change',
          },
        ],
        coverImg: [
          {
            required: true,
            message: '请上传商品封面图',
            trigger: 'change',
          },
        ],
        isPromotion: [
          {
            required: true,
            message: '请选择是否促销商品',
            trigger: 'change',
          },
        ],
        isShowInBrand: [
          {
            required: true,
            message: '请选择是否显示在对应店铺',
            trigger: 'change',
          },
        ],
        isGrounding: [
          {
            required: true,
            message: '请选择是否上架',
            trigger: 'change',
          },
        ],
        promotionTime: [
          {
            required: true,
            message: '请选择活动时间',
            trigger: 'change',
          },
        ],
        detail: [
          {
            required: true,
            message: '请填写商品详情',
            trigger: 'change',
          },
        ],
      },
      // 单规格设置校验对象
      rosRules: {
        inventory: [
          {
            required: true,
            message: '请输入库存',
            trigger: 'change',
          },
        ],
        inventoryAlert: [
          {
            required: true,
            message: '请输入库存预警',
            trigger: 'change',
          },
        ],
        platformPrice: [
          {
            required: true,
            message: '请输入尊享价',
            trigger: 'change',
          },
        ],
        costPrice: [
          {
            required: true,
            message: '请输入成本价',
            trigger: 'change',
          },
        ],
        crossedPrice: [
          {
            required: true,
            message: '请输入指导价',
            trigger: 'change',
          },
        ],

        depositPercentage: [
          {
            required: true,
            message: '请输入定金取值方式',
            trigger: 'change',
          },
          {
            validator: rmbLength,
            required: true,
            message: '不允许超过3位数',
            trigger: 'change',
          },
          {
            validator: validateRmbRos,
            required: true,
            message: '请输入正整数',
            trigger: 'change',
          },

          {
            validator: validateYuan,
            required: true,
            message: '请输入正数',
            trigger: 'change',
          },
        ],
      },
      // 多规格设置校验对象
      mulRules: {
        purchaseRealValue: [
          {
            required: true,
            message: '请输入定金取值方式',
            trigger: 'change',
          },
        ],

        depositPercentage: [
          {
            required: true,
            message: '请输入定金取值方式',
            trigger: 'change',
          },
          {
            validator: rmbLengthMul,
            required: true,
            message: '不允许超过3位数',
            trigger: 'change',
          },
          {
            validator: validateRmbMul,
            required: true,
            message: '请输入正整数',
            trigger: 'change',
          },

          {
            validator: validateYuanMul,
            required: true,
            message: '请输入正数',
            trigger: 'change',
          },
        ],
      },
      // sku列表
      tableColumnList: {
        tableHeaderList: [
          {
            prop: 'specificationsName',
            label: '规格值',
            showMethod: 'number',
          },
          {
            prop: 'previewImg',
            label: '预览图',
            showMethod: 'img',
          },
          {
            prop: 'platformPrice',
            label: '尊享价（元）',
            require: true,
            showMethod: 'input',
          },
          // {
          //   prop: 'costPrice',
          //   label: '成本价（元）',
          //   // require:true,
          //   showMethod: 'input',
          // },
          {
            prop: 'crossedPrice',
            label: '指导价（元）',
            // require:true,
            showMethod: 'input',
          },
          {
            prop: 'inventory',
            label: '库存',
            // require:true,
            showMethod: 'input',
          },
          {
            label: '库存预警',
            prop: 'inventoryAlert',
            // require:true,
            showMethod: 'input',
          },
          {
            label: '商品重量（kg）',
            prop: 'weight',
            // require:true,
            showMethod: 'input',
          },
        ],
        tableBodyList: [
          /*           [
                      { "index": "44", "previewImg": "", "platformPrice": 1, "crossedPrice": 2, "inventory": 3, "inventoryAlert": 4 },
                      { "index": "4", "previewImg": "", "platformPrice": 1, "crossedPrice": 2, "inventory": 3, "inventoryAlert": 4 }
                    ] */
        ],
      },
      // 商品规格
      items: [
        {
          groupName: '', // 规格分组名
          detail: [], // 规格名称数组
          inputVisible: false,
          inputValue: '',
        },
      ],
      // 接口存储对象：five step
      interfaceObj: {
        addApiName: addGoodsBaseType,
        editApiName: editGoodsBaseType,
        detApiName: getGoodsBaseInfo,
        groupApiName: getGoodsTypeList,
        freightApiName: freightTemplateList,
      },
    };
  },
  watch: {
    items: {
      handler(newval) {
        if (
          this.tableColumnList.tableBodyList.length < newval.length
        ) {
          this.tableColumnList.tableBodyList.push([]);
        }
        for (let index = 0; index < newval.length; index++) {
          const length = newval[index].detail.length;
          if (
            this.tableColumnList.tableBodyList[index].length < length
          ) {
            this.tableColumnList.tableBodyList[
              this.tableBodyListIndex
            ].push({
              specificationsName:
                index == this.tableBodyListIndex
                  ? newval[index].detail[length - 1]
                  : '',
              previewImg: '',
              platformPrice: '',
              costPrice: '',
              crossedPrice: '',
              inventory: '',
              inventoryAlert: '',
              weight: '',
            });
          }
        }
        // newval.forEach((item,index) => {
        //   const length = item.detail.length;
        //   if (
        //     this.tableColumnList.tableBodyList[this.tableBodyListIndex].length <
        //     length
        //   ) {
        //     this.tableColumnList.tableBodyList[this.tableBodyListIndex].push({
        //       specificationsName: index == this.tableBodyListIndex ? item.detail[length - 1] : '',
        //       previewImg: '',
        //       platformPrice: '',
        //       costPrice: '',
        //       crossedPrice: '',
        //       inventory: '',
        //       inventoryAlert: '',
        //       weight: '',
        //     });
        //   }
        // });
      },
      deep: true,
    },
  },
  created() {
    // 获取商品分组和运费模板
    this.$nextTick(() => {
      // this.network().getGroup();
      this.network().getFreight();
    });
    const { uuid = '' } = this.$route.params;
    if (uuid) {
      this.form.id = uuid;
      this.loading = true;
      this.$nextTick(() => {
        this.loadingForm = true;
        setTimeout(() => {
          this.network().getDetail();
        }, 200);
      });
    } else {
      this.loadingForm = true;
    }
  },
  methods: {
    changeNum(val, index) {
      const str = String(val.row[val.column.property]);
      if (str && str.indexOf('.') !== -1) {
        const arr = str.split('.');
        if (arr[1].length > 2) {
          this.$message.warning(`限小数点后${2}位`);
          val.row[val.column.property] = Number(str).toFixed(2);
        }
      }
    },
    getObj() {
      const obj = {
        ...this.form,
        carousel: this.form.carousel.join(','),
        createBy: this.$store.state.user.name,
        // 0单规格，1多规格
        specificationsType: this.isType,
        goodsTypeName: this.form.goodsTypeName,
        promotionStartTime: this.form.promotionTime[0],
        promotionEndTime: this.form.promotionTime[1],
        goodsTypeRos: this.form.goodsTypeRos.map((item) => {
          return {
            goodsId: this.form.id || '0',
            goodsTypeId: item.id,
            goodsTypeName: item.typeName,
            id: 0,
            isDelete: 0,
            params: {},
            parentGoodsTypeId: item.parentTypeId,
            remark: '',
            searchValue: '',
          };
        }),
        goodsSpecificationsGroupRos: this.items.map((item, index) => {
          return {
            groupName: item.groupName,
            isDelete: 0,
            createBy: this.$store.state.user.name,
            params: {},
            remark: '',
            searchValue: '',
            // 规格名称数组，type:1多规格。0单规格
            goodsSpecificationsRos:
              this.isType == 0
                ? [
                    {
                      createBy: this.$store.state.user.name,
                      ...this.rosForm,
                    },
                  ]
                : (this.tableColumnList.tableBodyList[index] || [{}]).map(
                    (titem) => {
                      return {
                        createBy: this.$store.state.user.name,
                        ...titem,
                        // 单规格放入rosForm,多规格放入mulForm
                        ...this.mulForm,
                        specificationsName: titem.specificationsName,
                      };
                    }
                  ),
          };
        }),
      };

      return obj;
    },
    // 添加规格
    addPriSpec() {
      if (this.items.length >= 3)
        return this.$message.warning('最多添加3个商品规格');
      this.items.push({
        groupName: '',
        detail: [],
        inputVisible: false,
        inputValue: '',
      });
    },
    delPrivateSpec(index) {
      this.items.splice(index, 1);
      this.tableColumnList.tableBodyList.splice(index, 1);
    },
    handleInputConfirm(val, attr) {
      if (val) {
        attr.detail.push(val);
      }
      attr.inputVisible = false;
      attr.inputValue = '';
    },
    handleClose(tag, item, index) {
      this.tableBodyListIndex = index;
      const itemIndex = item.detail.findIndex((item) => item === tag);
      item.detail.splice(item.detail.indexOf(tag), 1);
      this.tableColumnList.tableBodyList[
        this.tableBodyListIndex
      ].splice(itemIndex, 1);
    },
    showInput(attr, index) {
      this.tableBodyListIndex = index;
      attr.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs[`saveTagInput${index}`][0].$refs.input.focus();
      });
    },
    cancel() {
      this.$router.go(-1);
    },
    submit() {
      const throttleStatus = this.throttle(); // 节流
      if (!throttleStatus) return;
      // "queryForm", "rosForm","mulForm"三个进行判断
      let allValid = true;
      this.getObj();
      ['queryForm', 'rosForm', 'mulForm'].some((formName) => {
        console.log(formName)
        console.log(this.rosForm)
        if (this.$refs[formName]) {
          this.$refs[formName].validate((valid, val) => {
            if (!valid) {
              allValid = false;
              if (this.timer) clearTimeout(this.timer);
              this.timer = setTimeout(() => {
                this.$message.warning(
                  val[Object.keys(val)[0]][0].message
                );
                return true;
              }, 0);
            }
          });
        }
      });
      this.getObj();
      if (allValid) {
        if (this.form.id !== undefined) {
          this.getObj();
          this.network().editForm();
        } else {
          this.network().addForm();
        }
      }
    },

    network() {
      return {
        // 获取分类
        getGroup: async () => {
          const { groupApiName } = this.interfaceObj;
          const { code, rows } = await groupApiName({ type: this.type });
          // console.log(rows);
          if (code === 0) {
            const goodsTypeName = this.formList.findIndex(
              (item) => item.name === 'goodsTypeName'
            );
            this.formList[goodsTypeName].list = rows.map((item) => {
              item.children = item.martBrandTypeVos;
              return item;
            });
          }
          return rows;
        },
        // 获取所属品牌列表
        /*         getBrandList: async () => {
          const { rows, code } = await getBrandList();
          if (code === 0) {
            const brandId = this.formList.findIndex(
              (item) => item.name === 'brandId'
            );
            this.formList[brandId].list = rows.map((item) => {
              return {
                ...item,
                name: item.brandName,
                value: item.id,
              };
            });
          }
          return null;
        }, */
        // 获取运费模板
        getFreight: async () => {
          const { freightApiName } = this.interfaceObj;
          const { code, rows } = await freightApiName();
          if (code === 0) {
            const freightTemplateId = this.formList.findIndex(
              (item) => item.name === 'freightTemplateId'
            );
            this.formList[freightTemplateId].list = rows.map((item) => {
              return {
                ...item,
                name: item.templateName,
                value: item.id,
              };
            });
            // console.log(this.formList[freightTemplateId].list);
          }
        },
        // 详情
        getDetail: async () => {
          const { detApiName } = this.interfaceObj;
          const { data } = await detApiName(this.form.id);

          if (data) {
            Object.assign(this.form, data, {
              carousel:
                typeof data.carousel === 'string'
                  ? data.carousel.split(',')
                  : [],
            });
            // 活动时间合并
            this.form.promotionTime[0] =
              data.promotionStartTime || '';
            this.form.promotionTime[1] = data.promotionEndTime || '';

            this.isType = data.specificationsType;
            this.form.goodsTypeRos = this.form.goodsTypeRos.filter(
              (item) => item.goodsTypeName
            );
            this.form.goodsTypeName = data.goodsTypeRos
              .map((item) =>
                item.goodsTypeName ? item.goodsTypeId : null
              )
              .filter((item) => item)
              .join();
            // 单规格数据
            Object.assign(
              this.rosForm,
              data.goodsSpecificationsGroupRos[0]
                ?.goodsSpecificationsRos[0] || {}
            );
            // 多规格数据
            // 全款
            this.mulForm.depositPercentage =
              this.rosForm.depositPercentage;
            // 积分百分比
            this.mulForm.pointDeductionPercentage =
              this.rosForm.pointDeductionPercentage;
            // 购买方式
            this.mulForm.purchaseType = this.rosForm.purchaseType;
            this.items = data.goodsSpecificationsGroupRos.map(
              (item) => {
                return {
                  groupName: item.groupName, // 规格分组名
                  detail: item.goodsSpecificationsRos.map(
                    (Ritem) => Ritem.specificationsName
                  ), // 规格名称数组
                  inputVisible: false,
                  inputValue: '',
                };
              }
            );
            this.tableColumnList.tableBodyList =
              data.goodsSpecificationsGroupRos.map((item) => {
                return item.goodsSpecificationsRos.map((Ritem) => {
                  return {
                    specificationsName: Ritem.specificationsName,
                    previewImg: Ritem.previewImg,
                    platformPrice: Ritem.platformPrice,
                    costPrice: Ritem.costPrice,
                    crossedPrice: Ritem.crossedPrice,
                    inventory: Ritem.inventory,
                    inventoryAlert: Ritem.inventoryAlert,
                    weight: Ritem.weight,
                  };
                });
              });
            // Object.assign(this.rosFor, data);
          }
          this.loading = false;
        },
        // 新增
        addForm: async () => {
          if (
            this.tableColumnList.tableBodyList.length < 1 &&
            this.isType == 1
          )
            return this.$message.warning('请添加商品规格');
          if (this.isType == 0) {
            const obj = {
              ...this.getObj(),
              createBy: this.$store.state.user.name,
            };
            const { addApiName } = this.interfaceObj;
            const { code } = await addApiName({
              ...obj,
              type: this.type,
            });
            if (code === 0) {
              this.$modal.msgSuccess('新增成功');
              this.resetForm('queryForm');
              this.$router.go(-1);
            }
            return;
          }
          // 其中的内容有一项为空则提示
          // { "index": "44", "previewImg": "", "platformPrice": 1, "crossedPrice": 2, "inventory": 3, "inventoryAlert": 4 },
          this.tableColumnList.tableBodyList.some((item) => {
            item.some(async (titem) => {
              if (
                !this.isAllPropertiesNumeric(titem, [
                  'previewImg',
                  'specificationsName',
                  'costPrice',
                ])
              ) {
                this.$message.warning('请完善规格信息');
                return true;
              } else {
                const obj = this.getObj();
                const { addApiName } = this.interfaceObj;
                const { code } = await addApiName({
                  ...obj,
                  type: this.type,
                });
                if (code === 0) {
                  this.$modal.msgSuccess('新增成功');
                  this.resetForm('queryForm');
                  this.$router.go(-1);
                }
              }
            });
          });
        },
        // 编辑
        editForm: async () => {
          if (
            this.tableColumnList.tableBodyList.length < 1 &&
            this.isType == 1
          )
            return this.$message.warning('请添加商品规格');
          // 其中的内容有一项为空则提示
          if (this.isType == 0) {
            this.getObj();

            const obj = {
              ...this.getObj(),
              updateBy: this.$store.state.user.name,
            };
            const { editApiName } = this.interfaceObj;
            const { code } = await editApiName({
              ...obj,
              type: this.type,
            });
            if (code === 0) {
              this.$modal.msgSuccess('新增成功');
              this.resetForm('queryForm');
              this.$router.go(-1);
            }
            return;
          }
          const hasIncompleteItem = this.tableColumnList.tableBodyList.some(
            (item) => {
              return item.some(async (titem) => {
                if (
                  !this.isAllPropertiesNumeric(titem, [
                    'previewImg',
                    'specificationsName',
                    'costPrice',
                  ])
                ) {
                  this.$message.warning('请完善规格信息');
                  return true;
                } else {
                  // this.form.goodsTypeRos = [];
                  this.form.goodsSpecificationsGroupRos = [];
                  const obj = this.getObj();

                  const { editApiName } = this.interfaceObj;
                  const { code } = await editApiName({
                    ...obj,
                    type: this.type,
                  });
                  if (code === 0) {
                    this.$modal.msgSuccess('编辑成功');
                    this.resetForm('queryForm');
                    this.$router.go(-1);
                  }
                  return true;
                }
              });
            });

          if (hasIncompleteItem) {
            // 如果有不完整的项，就停止执行
            return;
          }
        },
      };
    },
    // 字符串只包含数字通过
    isAllPropertiesNumeric(obj, skipProperties = []) {
      console.log(skipProperties);
      return Object.entries(obj).every(([key, value]) => {
        return (
          skipProperties.includes(key) ||
          (/^\d+(\.\d+)?$/.test(value) && value !== '')

          // (typeof value === 'string' && /^\d+$/.test(value))
        );
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.goodsdetails {
  height: 100%;
  width: 100%;
  background: #ffffff;
  padding: 30px;
}

.goodsdetails .demo-ruleForm {
  width: 100%;
}

.goodsdetails .demo-ruleForm > div {
  width: 80%;
}

.goodsdetails .el-tag + .el-tag {
  margin-left: 10px;
}

.goodsdetails .button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.goodsdetails .input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.goods-spec {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  height: 36px;
}

.goods-spec .goods-spec-add {
  margin-right: 15px;
}

.goods-container .button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.goods-container .input-new-tag {
  width: 90px;
  margin-right: 10px;
  vertical-align: bottom;
}

.goods-container .el-tag {
  margin-right: 10px;
}

.goods-container .goods-content {
  margin-bottom: 10px;
  padding: 14px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fcfcfc;
}

.goods-content .goods-content-box {
  display: flex;
  align-items: center;
}

.goods-content-box .goods-content-left {
  flex: 1;
}
::v-deep .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .dankal-image-upload p .close {
  top: 0px !important;
  right: -7px !important;
}
::v-deep .dankal-image-upload div .add {
  width: 95px !important;
  height: 95px !important;
}
::v-deep .dankal-image-upload .el-image {
  width: 95px !important;
  height: 95px !important;
  margin-right: 0 !important;
  margin-top: 5px !important;
}
</style>

<style>
.editManage .el-table th.el-table__cell > .cell::before {
  content: '*';
  padding-right: 4px;
  color: red;
}

.editManage .el-table th.el-table__cell:nth-child(1) > .cell::before,
.editManage .el-table th.el-table__cell:nth-child(2) > .cell::before,
.editManage .el-table th.el-table__cell:nth-last-child(2) > .cell::before {
  content: '';
}
</style>
